package day05;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @Description: 在窗口中将迟到元素发送到侧输出流中
 * @Author: ZYX
 * @Date: 2022/2/14 10:35
 * @Version: 1.0
 */
public class Demo03 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env.addSource(new SourceFunction<String>() {
            @Override
            public void run(SourceContext<String> context) throws Exception {

                context.collectWithTimestamp("a", 1000L);
                context.emitWatermark(new Watermark(999L));
                context.collectWithTimestamp("a", 2000L);
                context.emitWatermark(new Watermark(1999L));
                context.collectWithTimestamp("a", 4000L);
                context.emitWatermark(new Watermark(4999L));
                context.collectWithTimestamp("a", 3000L);

            }

            @Override
            public void cancel() {

            }
        }).keyBy(obj -> 1)
                // 窗口时间区间设置
                .window(TumblingEventTimeWindows.of(Time.seconds(5L)))
                .sideOutputLateData(new OutputTag<String>("late"){})
                .process(new ProcessWindowFunction<String, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer value, Context context, Iterable<String> iterable, Collector<String> out) throws Exception {
                        out.collect("窗口中共有：" + iterable.spliterator().getExactSizeIfKnown());
                    }
                });
        result.print();

        result.getSideOutput(new OutputTag<String>("late"){}).print("late:");

        env.execute();
    }

}
